#define _CRT_SECURE_NO_WARNINGS 1

class Solution {
public:
    int takeCharacters(string s, int k) {
        int left = 0, right = s.size() - 1;
        vector<int> count(3, 0);
        int flag = 0, n = s.size();
        int res = 0;
        if (k == 0) return 0;
        if (n < 3) return -1;
        while (left < n && flag < 3)
        {
            flag = 0;
            ++count[s[left] - 'a'];
            for (int i = 0; i < 3; i++)
            {
                if (count[i] >= k) flag++;
            }
            left++;
        }
        if (left >= n && flag != 3) return -1;
        res = left;
        --left;

        while (left < n && left >= 0 && right >= 0)
        {
            while (left >= 0 && flag == 3)
            {
                flag = 3;
                --count[s[left] - 'a'];
                for (int i = 0; i < 3; i++)
                {
                    if (count[i] < k) flag--;
                }
                if (flag == 3)
                {
                    int tmp = left + n - right - 1;
                    if (tmp < res) res = tmp;
                }
                left--;
            }
            // for(auto e : count)
            // {
            //     cout << e << ' ';
            // }
            // cout << left << endl;

            while (right >= 0 && flag < 3)
            {
                flag = 0;
                ++count[s[right] - 'a'];
                for (int i = 0; i < 3; i++)
                {
                    if (count[i] >= k) flag++;
                }
                right--;
            }

            // for(auto e : count)
            // {
            //     cout << e << ' ';
            // }
            // cout << right << endl << endl;
        }
        return res;
    }
};